import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import router from "@/router";

const request = axios.create({
    // 基础路径
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 超时时间
    timeout: 5000,
});

let userStore: ReturnType<typeof useUserStore> | null;

const getUserStore = () => {
    if (!userStore) {
        userStore = useUserStore();
    }
    return userStore;
}

// 添加请求与响应拦截器
request.interceptors.request.use((config) => {
    const token = getUserStore().token;
    if (token) {
        config.headers.token = token
    }
    return config
})

// 响应拦截器
request.interceptors.response.use((response) => {
    const code = response.data.code;
    if (code != 200) {
        // 处理token失效
        switch (code) {
            case 401:
            case 403:
                getUserStore().logout();
                // 跳轉至登入頁面
                router.push('/login');
                break;
        }
        console.log(`请求失败url:${response.config.url},===>${response.data.message}`);
        // ElNotification({
        //     type: 'error',
        //     message: response.data.message
        // })
        // 非200 状态码，抛出错误
        return Promise.reject(response.data);
    }
    return response.data;
}, (error) => {
    let msg = '';
    const status = error.response.status;
    switch (status) {
        case 404:
            msg = "请求地址错误";
            break;
        case 500:
            msg = "服务器出现问题";
            break;
        default:
            msg = "无网络";
    }
    ElMessage({
        type: 'error',
        message: msg
    })
    return Promise.reject(error);
})

export default request;
